package com.springboot.fram.core.digest.codec;

/**
 * Hex编码
 *
 * @author TaoYu
 */
public final class Hex {

  /**
   * 编码
   *
   * @param bytes 字节数组
   * @return hex字符串
   */
  public static String encode(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int n = 0; n < bytes.length; n++) {
      String strHex = Integer.toHexString(bytes[n] & 0xFF);
      sb.append((strHex.length() == 1) ? "0" + strHex : strHex);
    }
    return sb.toString();
  }

  /**
   * 解码
   *
   * @param hex hex字符串
   * @return 字节数组
   */
  public static byte[] decode(String hex) {
    char[] arr = hex.toCharArray();
    byte[] b = new byte[hex.length() / 2];
    for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
      b[j] = Integer.valueOf(Integer.parseInt("" + arr[i++] + arr[i], 16) & 0xFF).byteValue();
    }
    return b;
  }

}
